﻿using System.Collections.Generic;
using System.IO;
using System.Collections.ObjectModel;

namespace Babylon.Importers
{
    internal class Document<T> where T : Line, new()
    {
        readonly ReadOnlyCollection<ReadOnlyCollection<T>> blocks;

        public Document(Stream source)
        {
            using (StreamReader reader = new StreamReader(source))
            {
                int lineIndex = 0;
                List<T> tempLines = null;
                List<ReadOnlyCollection<T>> tempBlocks = new List<ReadOnlyCollection<T>>();
                string previousHeader = "";

                while (!reader.EndOfStream)
                {
                    T line = new T {Index = lineIndex++};
                    line.SetLine(reader.ReadLine());

                    if (line.IsValid)
                    {
                        if ((line.Tokens[0] == line.BlockSperator && previousHeader != line.BlockSperator) || tempLines == null)
                        {
                            tempLines = new List<T>();
                            tempBlocks.Add(new ReadOnlyCollection<T>(tempLines));
                        }
                        tempLines.Add(line);
                        previousHeader = line.Tokens[0];
                    }
                }

                blocks = new ReadOnlyCollection<ReadOnlyCollection<T>>(tempBlocks);
            }
        }

        public ReadOnlyCollection<ReadOnlyCollection<T>> Blocks
        {
            get { return blocks; }
        }
    }
}
